<?php
//$Id: SystemClass.inc.php 2 2012-07-10 01:08:43Z 5330056@qq.com $
class systemClass extends CommonClass
{

	static public $_server_id = 1;
	static public $_db_name = '';
	static private $_tbl_name = 'Bin_Server_loagavg';
	static public $_load_time = 600;
	
	static public function get_loadavg()
	{
		if(stristr(PHP_OS, 'win'))
		{
			$wmi = new COM('"Winmgmts://');
			$server = $wmi->execquery('SELECT LoadPercentage FROM Win32_Processor');
			$cpu_num = $load_total = 0;
			foreach($server as $cpu)
			{
				$cpu_num++;
				$load_total += $cpu->loadpercentage;
			}
			$load = ($load_total/$cpu_num);
		}
		else
		{
			$sys_load = sys_getloadavg();
			$load = $sys_load[0];
		}
		return  $load;
	}

	static public function input_load_to_db_and_get_min_server($host_name, $load)
	{
		
		if(empty($host_name))
		{
			return false;
		}
		
		$cache_obj = Bin::singtolen('cache_class', 'common');
		
		list($host_name, $load) = array(trim($host_name), intval($load));
		$sql = 'INSERT INTO '.self::$_db_name.'.'.self::$_tbl_name.' (`host_name`, `load`, `add_time`)VALUES("'.$host_name.'", '.$load.', '.$_SERVER['REQUEST_TIME'].');';
		$sql .= 'DELETE FROM '.self::$_db_name.'.'.self::$_tbl_name.' WHERE `add_time` < '.($_SERVER['REQUEST_TIME'] - self::$_load_time).';';
		
		$cache_key = '___system_Bin_server_loadavg_cache_key';
		$cache_data = $cache_obj->get_cache($cache_key);
		if(empty($cache_data))
		{
			$sql .= 'SELECT host_name, COUNT(*) AS c FROM '.self::$_db_name.'.'.self::$_tbl_name.' GROUP BY host_name;';
			$rs = self::$_DB->query_sql($sql, self::$_server_id, false);
			$sql = '';
			foreach($rs[0] as $t)
			{
				$sql .= "SELECT host_name, SUM(`load`) / {$t['c']} as loadavg FROM ".self::$_db_name.'.'.self::$_tbl_name." WHERE host_name='{$t['host_name']}';";				
			}
			$rs = self::$_DB->query_sql($sql, self::$_server_id, false);
			foreach($rs[0] as $t)
			{
				$r[$t['host_name']] = intval($t['loadavg']);
			}
			asort($r);
			$rs = array_keys(array_slice($r, 0, 1));
			$cache_obj->save_cache($cache_key, $rs[0], 300);
		}
		else 
		{
			self::$_DB->query_sql($sql, self::$_server_id, false);
			$rs = $cache_data;
		}
		
		return  $rs[0];
	}
}
?>